package com.shushan.pages;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.exam.ExamActivity;
import com.shushan.exam.OnResultCollectListener;
import com.shushan.exam.bean.ExerciseBean;
import com.shushan.exam.bean.PaperBean;
import com.shushan.home.adapter.ExerciseRecordScoreAdapter;
import com.shushan.home.bean.RewardTimeBean;
import com.shushan.mixedexam.bean.MutiExercisePaperBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.bean.ExerciseRecordDetailsBean;
import com.shushan.pages.bean.PaperInfoBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.util.DateUtils;
import com.shushan.util.Session;

/**
 * @ClassName: RecordResultActivity
 * @Desciption: //练习记录结果页面
 * @author: zhangshihao
 * @date: 2018-04-24
 */
public class RecordResultActivity extends BaseActivity implements View.OnClickListener,
        OnResultCollectListener {

    private static final String TAG = RecordResultActivity.class.getSimpleName();

    private int paperId;
    private String create_time;
    private String practiceType;
    private int timeConsuming;

    private ImageView ivBack;
    private TextView tvTitle;
    private ImageView ivExamAgain;
    private TextView tvChineseScore;
    private TextView tvMathScore;
    private TextView tvEnglishScore;
    private TextView tvDate;
    private TextView tvTime;
    private TextView tvExamCostTime;
    private TextView tvGetTime;
    private TextView tvMissionCompleteSubjects;
    private ImageView ivWatchTopics;
    private RecyclerView recyclerView;
    private ImageView ivGoTop;
    private ScrollView scrollView;

    private ExerciseRecordScoreAdapter exerciseRecordScoreAdapter;
    private MutiExercisePaperBean paperBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_result);
        Intent intent = getIntent();
        paperId = intent.getIntExtra("paper_id", 0);
        create_time = intent.getStringExtra("create_time");
        practiceType = intent.getStringExtra("practice_type");
        initView();
        getData();
    }

    private void initView() {
        ivBack = findViewById(R.id.top_left_back_img);
        tvTitle = findViewById(R.id.exam_title_tv);
        ivExamAgain = findViewById(R.id.exam_title_img);
        tvChineseScore = findViewById(R.id.tv_chinese_score);
        tvMathScore = findViewById(R.id.tv_math_score);
        tvEnglishScore = findViewById(R.id.tv_english_score);
        tvDate = findViewById(R.id.tv_date);
        tvTime = findViewById(R.id.tv_time);
        tvExamCostTime = findViewById(R.id.exam_score_time_tv);
        tvGetTime = findViewById(R.id.tv_get_time);
        tvMissionCompleteSubjects = findViewById(R.id.tv_mission_complete_subjects);
        ivWatchTopics = findViewById(R.id.exam_score_look_img);
        recyclerView = findViewById(R.id.exam_score_lv);
        ivGoTop = findViewById(R.id.exam_score_scroll_top_img);
        scrollView = findViewById(R.id.exam_score_sv);

        ivExamAgain.setOnClickListener(this);
        ivWatchTopics.setOnClickListener(this);
        ivGoTop.setOnClickListener(this);
    }

    private void getData() {
        int child_id = BabyApplication.getInstance().getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.EXERCISE_DETAILS);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", child_id)
                .putValue("paper_id", paperId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<ExerciseRecordDetailsBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(ExerciseRecordDetailsBean exerciseRecordDetailsBean) {
                        updateUIbyData(exerciseRecordDetailsBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void updateUIbyData(ExerciseRecordDetailsBean exerciseRecordDetailsBean) {
        PaperInfoBean paperInfoBean = exerciseRecordDetailsBean.paperInfoBean;
        if (paperInfoBean.chinese_score <= 0) {
            tvChineseScore.setText(0+"分");
        } else {
            tvChineseScore.setText(paperInfoBean.chinese_score/100+"分");
        }
        if (paperInfoBean.math_score <= 0) {
            tvMathScore.setText(0+"分");
        } else {
            tvMathScore.setText(paperInfoBean.math_score/100+"分");
        }
        if (paperInfoBean.english_score <= 0) {
            tvEnglishScore.setText(0+"分");
        } else {
            tvEnglishScore.setText(paperInfoBean.english_score/100+"分");
        }
        timeConsuming = paperInfoBean.time_consuming;
        tvExamCostTime.setText(getTimeConsumingStr(timeConsuming));
        tvDate.setText(DateUtils.captureDateByFormat(create_time, "yyyy-MM-dd"));
        tvTime.setText(DateUtils.captureTimeWithoutSecond(create_time));

        paperBean = new MutiExercisePaperBean();
        paperBean.setChineseExerciseBeans(exerciseRecordDetailsBean.chineseExerciseBeans);
        paperBean.setMathExerciseBeans(exerciseRecordDetailsBean.mathExerciseBeans);
        paperBean.setEnglishExerciseBeans(exerciseRecordDetailsBean.englishExerciseBeans);
        paperBean.paperInfoBean.id = paperInfoBean.id;
        paperBean.paperInfoBean.outline_id = paperInfoBean.outline_id;
        paperBean.paperInfoBean.special_id = paperInfoBean.special_id;
        paperBean.paperInfoBean.video_id = paperInfoBean.video_id;
//        exerciseRecordScoreAdapter = new ExerciseRecordScoreAdapter(this, paperBean);
        exerciseRecordScoreAdapter.setOnResultCollectListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(exerciseRecordScoreAdapter);
    }

    private String getTimeConsumingStr(int second) {
        int minute = second / 60;
        int restSecond = second % 60;
        String consumingStr = "";
        if (minute > 9 && restSecond > 9) {
            consumingStr = String.valueOf(minute) + ":" + String.valueOf(restSecond);
        } else if (minute > 9 && restSecond < 10) {
            consumingStr = String.valueOf(minute) + ":" + "0" + String.valueOf(restSecond);
        } else if (minute < 10 && restSecond < 10) {
            consumingStr = "0" + String.valueOf(minute) + ":" + "0" + String.valueOf(restSecond);
        } else if (minute < 10 && restSecond > 9) {
            consumingStr = "0" + String.valueOf(minute) + ":" + String.valueOf(restSecond);
        }
        return consumingStr;
    }

    @Override
    public void onResultCollect(ExerciseBean exerciseBean) {
        if (exerciseBean == null) {
            return;
        }

        if (exerciseBean.child_collect == 0) {
            doPostCollect(1, exerciseBean);
        } else {
            doPostCollect(2, exerciseBean);
        }
    }

    /**
     * 收藏和取消收藏
     *
     * @param collectType 1:收藏试题2:取消收藏试题
     */
    private void doPostCollect(final int collectType, final ExerciseBean exerciseBean) {
        int childId = BabyApplication.getInstance().getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this,UrlConst.BASE_URL).appendRegion(UrlConst.TOPIC_COLLECT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("exercise_id", exerciseBean.id)
                .putValue("subject_id", exerciseBean.subject_id)
                .putValue("exercises_type", Integer.parseInt(practiceType))
                .putValue("type", collectType + "");

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        if (exerciseBean.child_collect == 1) {
                            exerciseBean.child_collect = 0;
                        } else {
                            exerciseBean.child_collect = 1;
                        }

                        exerciseRecordScoreAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.exam_title_img://重考
                examAgain();
                break;
            case R.id.exam_score_look_img://查看习题
                if(paperBean != null){
                    Session.getSession().put("paperBean",paperBean);

                    Intent intent = new Intent(this,RecordDetailActivity.class);
                    intent.putExtra("practiceType",practiceType);
                    intent.putExtra("timeConsuming",getTimeConsumingStr(timeConsuming));
                    startActivityAllow(intent);
                }else {
                    showToast("数据为空");
                    return;
                }
                break;
            case R.id.exam_score_scroll_top_img:
                scrollView.scrollTo(0, 0);
                break;
        }
    }

    private void examAgain() {
        onBackAction();

        Session.getSession().put("examPaperBean", paperBean);

        Intent intent = new Intent(RecordResultActivity.this, ExamActivity.class);
        intent.putExtra("awardType", 3);
        intent.putExtra("fromResultType", 0);
        intent.putExtra("paperId", paperId);
        startActivityAllow(intent);
    }

}
